package com.antoco.controlcenter.view;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.antoco.controlcenter.base.BaseApplication;
import com.antoco.controlcenter.iface.IRecodeEventListener;
import com.antoco.controlcenter.utils.ToastUtils;

import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;
import org.videolan.libvlc.util.VLCVideoLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class VlcManager {
    private static final boolean USE_TEXTURE_VIEW = false;
    private static final boolean ENABLE_SUBTITLES = true;

    private String TAG_vlc = "VlcManager:";

    private VLCVideoLayout mVideoLayout; //依附播放控件

    private LibVLC mLibVLC; //VlcLib
    private MediaPlayer mMediaPlayer; //播放
    private MediaPlayer mMediaRecorder; //录像
    private Context context;
    private IRecodeEventListener iRecodeEventListener;
    private boolean isRecording = false;
    private String url;

    public VlcManager(Context context, VLCVideoLayout videoLayout) {
        this.context = context;

        mVideoLayout = videoLayout;
        final ArrayList<String> args = new ArrayList<>();//VLC参数
//        args.add("--rtsp-tcp");//强制rtsp-tcp，加快加载视频速度
//        args.add("--live-caching=0");
//        args.add("--file-caching=0");
//        args.add("--network-caching=0");//增加实时性，延时大概2-3秒
        mLibVLC = new LibVLC(context, args); //初始化SDK
        mMediaPlayer = new MediaPlayer(mLibVLC);
        mMediaPlayer.attachViews(mVideoLayout, null, ENABLE_SUBTITLES, USE_TEXTURE_VIEW);

    }

    public void setFullSrcee(){
        mMediaPlayer.getVLCVout().setWindowSize(context.getResources().getDisplayMetrics().widthPixels, context.getResources().getDisplayMetrics().heightPixels);
        mMediaPlayer.setScale(2);
    }

    public void play(String url) {
        this.url = url;
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            mMediaPlayer.stop();
        }

        Log.d(TAG_vlc, "开始播放视频:" + url);
        Media media = new Media(mLibVLC, Uri.parse(url));
//        media.addOption(":file-caching=200");
        media.addOption(":network-caching=200");//网络缓存
//        media.addOption(":live-caching=0");//直播缓存
//        media.addOption(":rtsp-caching=200");//rtsp缓存
//        media.addOption(":sout-mux-caching=0");//输出缓存
      //  media.setHWDecoderEnabled(false, false);//设置后才可以录制和截屏
        mMediaPlayer.setMedia(media);

        media.release();
        mMediaPlayer.setVideoScale(MediaPlayer.ScaleType.SURFACE_FILL);
        mMediaPlayer.play();
    }


    public boolean isPlaying() {
        return (mMediaPlayer != null && mMediaPlayer.isPlaying());
    }

    public boolean isRecording() {
        return isRecording;
    }

    public String recordStart(String path) {
        String destination = null;
        if (isPlaying()) //视频正在播放
        {
            isRecording = true;
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            destination = path + "/" + formatter.format(new Date(System.currentTimeMillis())) + ".mp4"; //视频录制路径
            if (mMediaRecorder == null) {
                Log.d("Media", "正在创建录像MediaPlayer对象...");
                mMediaRecorder = new MediaPlayer(mLibVLC);
                mMediaRecorder.setEventListener(new MediaPlayer.EventListener() {
                    @Override
                    public void onEvent(MediaPlayer.Event event) {
                        Log.d(TAG_vlc, event.type + "。。。。。。。。。。。。");
                        //录像成功
                        if (event.type == 260) {
                            Log.d(TAG_vlc, "开启录像成功");
                            if (null != iRecodeEventListener) {
                                isRecording = true;
                                iRecodeEventListener.onChangeRecode(true);
                            }
                        }
                    }
                });
            }
            Log.d(TAG_vlc, "开始录像:" + destination);
            Media media = new Media(mLibVLC, mMediaPlayer.getMedia().getUri()); //获取正在播放的视频地址
            media.addOption(":sout=#file{dst=" + destination + "}");
            media.addOption(":sout-display");
            media.addOption(":sout-all");
            media.addOption(":sout-keep");
            mMediaRecorder.setMedia(media);
            media.release();
            mMediaRecorder.play();
        } else {
            if (null != iRecodeEventListener) {
                isRecording = false;
                iRecodeEventListener.onChangeRecode(false);
            }
            Log.d("Media", "当前不存在正在播放的视频，无法开启录像");
        }
        return destination;
    }

    public void recordStop() {
        if (isRecording()) {
            ToastUtils.showToast(BaseApplication.getContext(), "退出录像");
            Log.d(TAG_vlc, "退出录像");
            mMediaRecorder.stop();
            iRecodeEventListener.onStopRecode();
            isRecording = false;
            return;
        }

        if (!isPlaying()) {
            iRecodeEventListener.onChangeRecode(false);
            return;
        }
    }


    //系统方法录屏,不能保证成功
    public void startRecord(String path) {
        if (!isRecording) {
            boolean ret = mMediaPlayer.record(path);
            isRecording = true;
        } else {
            boolean ret = mMediaPlayer.record(null);
            isRecording = false;
            Log.d(TAG_vlc, "停止录像");
        }
    }

    public void stopRecord() {
        mMediaPlayer.record(null);
    }

    public void stop() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.detachViews();
        }
    }

    public void onRestart() {
        if (!TextUtils.isEmpty(url)) {
            play(url);
        }
    }

    public void destroy() {
        if (null != mMediaPlayer) {
            mMediaPlayer.record(null);
            mMediaPlayer.release();
            mMediaPlayer.getVLCVout().detachViews();
        }
        if (null != mLibVLC) {
            mLibVLC.release();
        }
    }

    public void pause() {
        if (null != mMediaPlayer) {
            mMediaPlayer.record(null);
            mMediaPlayer.detachViews();
            mMediaPlayer.pause();
        }

    }

    public void setFloatScreen(int width, int height) {
    //    mMediaPlayer.getVLCVout().setWindowSize(width, height);
//        mMediaPlayer.getVLCVout().setWindowSize(width, width);
        mMediaPlayer.getVLCVout().setWindowSize(width, height);
       // mMediaPlayer.setAspectRatio(context.getResources().getDisplayMetrics().heightPixels + ":" + context.getResources().getDisplayMetrics().widthPixels);
       // mMediaPlayer.setAspectRatio( "16:9");//设置屏幕比例
        mMediaPlayer.setScale(0);
    }

    public String takeScreenShot() {
        String path = null;
        if (null == mMediaPlayer) {
            return path;
        }
        SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyyHHmmss");
        path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + formatter.format(new Date(System.currentTimeMillis())) + ".png";
//        if (mMediaPlayer.takeSnapShot(0, path, 0, 0)) {
//            ToastUtils.showToast(BaseApplication.getContext(), "图片已保存：" + path);
//            return path;
//        } else {
//            ToastUtils.showToast(BaseApplication.getContext(), "截图失败");
//            return null;
//        }
        return path;
    }

    public void spuTracksSub() {
        if (null == mMediaPlayer) {
            return;
        }
        MediaPlayer.TrackDescription[] spuTracks = mMediaPlayer.getVideoTracks();
        if (null == spuTracks) {
        }

        int curSubtitle = mMediaPlayer.getSpuTrack();
        mMediaPlayer.setAudioOutput("sdafa");
        String[] items = new String[spuTracks.length];
        int select = 0;
        for (int i = 0; i < spuTracks.length; i++) {
            items[i] = spuTracks[i].name;
            if (spuTracks[i].id == curSubtitle) {
                select = i;
            }
        }
        mMediaPlayer.setSpuTrack(spuTracks[0].id);
    }


    public void setiRecodeEventListener(IRecodeEventListener iRecodeEventListener) {
        this.iRecodeEventListener = iRecodeEventListener;
    }
}
